import { parseHTML } from "./html-parser";

export function parse(template, options) {
  const stack = [];
  let root, currentParent;

  function closeElement(element){
    if(currentParent) {
      currentParent.children.push(element)
      element.parent = currentParent
    }
  }

  parseHTML(template, {
    start(tag, attrs, start, end) {
      const element = createASTElement(tag, attrs, currentParent);
      if(!root) {
        root = element
      }
      console.log(element)
      // 设置parent
      currentParent = element
      stack.push(element)
    },
    end(tag, start, end) {
      const element = stack[stack.length - 1]
      stack.length -= 1
      currentParent = stack[stack.length - 1]
      closeElement(element)
    },
    chars(text, start, end) {
      if (!currentParent) {
        return
      }
      const children = currentParent.children
      if(text){
        // console.log('text',text)
      }
      // if (child) {
      //   children.push(child)
      // }
    },
  });

  return root;
}

export function createASTElement(tag, attrs, parent) {
  return {
    type:1,
    tag,
    attrsList:attrs,
    attrsMap:makeAttrsMap(attrs),
    rawAttrsMap:{},
    parent,
    children:[]
  }
}

function makeAttrsMap(attrs) {
  const map = {}
  for(let i = 0, l = attrs.length; i < l; i++ ){
    // todo 错误处理
    map[attrs[i].name] = attrs[i].value
  }
  return map
}
